package com.weseal.controller;

import com.google.zxing.WriterException;
import com.weseal.domain.User;
import com.weseal.google.utils.AuthenticatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author weseal
 * @title
 * @description
 * @usage
 * @copyright Copyright 2014  rrmj Corporation. All rights reserved.
 * @company 上海众多美网络科技有限公司
 * @create 2017/10/19
 */
@Controller
@RequestMapping("/userTest")
public class TestController {

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	private HttpServletResponse response;


	private static List<User> userList = new ArrayList<User>();

	private static Map<String, String> securityMap = new HashMap<String, String>();


	@RequestMapping("/initRegister")
	public String initRegister() {
		return "index";
	}

	@RequestMapping("/initLogin")
	public String initLogin() {
		return "login";
	}


	@RequestMapping("/register")
	public String register(User user, ModelMap map) {
		userList.add(user);
		map.put("userName", user.getUserName());
		return "qcCode";
	}

	@RequestMapping("/qrCode")
	public void qrCode(String userName) throws NoSuchAlgorithmException, WriterException, IOException {
		response.setContentType("image/png");
		String secureKey = AuthenticatorUtils.generateSecretKey();
		securityMap.put(userName, secureKey);
		BufferedImage bufferedImage = AuthenticatorUtils.getQRcodeBufferedImage(userName, secureKey);
		OutputStream stream = response.getOutputStream();
		ImageIO.write(bufferedImage, "png", stream);
		stream.flush();
		stream.close();
	}


	@RequestMapping("/login")
	public String login(User loginUser, ModelMap map) {
		if (!CollectionUtils.isEmpty(userList)) {
			for (User user : userList) {
				if (user.getUserName().equals(loginUser.getUserName()) &&
						user.getPassword().equals(loginUser.getPassword())) {
					String security = securityMap.get(user.getUserName());
					if (AuthenticatorUtils.authCode(loginUser.getCode(), security)) {
						return "main";
					} else {
						map.put("error", "qrCode is fault");
						return "error";
					}
				}
			}
		}
		map.put("error", "userName or password is fault");
		return "error";
	}


}
